import {
  selectOrganization,
  treeOrganization,
  updateOrganization
} from '@/services/api/api-admin-organization';
import { CloseOutlined, FolderOutlined, HomeOutlined } from '@ant-design/icons';
import ProForm, {
  DrawerForm,
  ProFormDigit,
  ProFormInstance,
  ProFormRadio,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-form';
import { Button, message, Spin } from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useRef, useState } from 'react';

interface EditOrganizationProps {
  data: AdminOrganizationData.Organization;
  onRefurbish: () => void;
}
const EditOrganization: React.FC<EditOrganizationProps> = ({ data, onRefurbish }) => {
  const formRef = useRef<ProFormInstance>();

  /**
   * 树形列表选择数据
   */
  const [organization, setOrganizationState] = useState<AdminOrganizationData.Organization>();

  /**
   * 初始化树形数据
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(datas: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (datas) {
      datas.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadTreeOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        setDataTreeState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 根据key加载组织详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await selectOrganization({ id: data.id });
      if (response.code === 0) {
        setOrganizationState(response.data);

        formRef.current?.setFieldsValue({
          parentName: response.data?.parentName,
          parentId: response.data?.parentId,
          seq: response.data?.seq,
          state: response.data?.state,
          name: response.data?.name,
          nickname: response.data?.nickname,
          avatar: response.data?.avatar,
          isFolder: response.data?.isFolder,
        });
      }
    } catch (error) {}
  };

  return (
    <>
      <DrawerForm
        key={'edit_organization'}
        title="编辑"
        drawerProps={{
          destroyOnClose: true,
        }}
        formRef={formRef}
        trigger={<Button type="primary">编辑</Button>}
        onOpenChange={(visible: boolean) => {
          if (visible) {
            loadTreeOrganizationData();
            loadOrganizationData();
          } else {
            setOrganizationState(undefined);
          }
        }}
        onFinish={async (values) => {
          try {
            if (values.parentName === undefined || values.parentId === undefined) {
              message.warning('请选择组织！');
              return false;
            }

            if (organization?.id === values.parentId) {
              message.warning('不能选择本组织为上级');
              return false;
            }

            const response = await updateOrganization({
              ...values,
              id: organization?.id,
            });
            if (response.code === 0) {
              message.success('提交成功');
              onRefurbish();
            }
          } catch (error) {
            message.success('提交失败');
          }
          return true;
        }}
      >
        <Spin spinning={organization === undefined}>
          <ProForm.Group>
            <ProFormText width="md" name="parentName" label="上级" disabled />
            <ProFormText hidden={true} width="md" name="parentId" label="上级组织" disabled />
            <ProFormDigit width="md" label="排序" name="seq" min={1} max={1000} />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText width="xl" name="avatar" label="头像" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              width="md"
              name="name"
              label="名称"
              rules={[{ required: true, message: '请输入名称' }]}
            />
            <ProFormText
              width="md"
              name="nickname"
              label="昵称"
              rules={[{ required: true, message: '请输入昵称' }]}
            />
            <ProFormTextArea width="xl" name="describes" label="描述" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormRadio.Group
              name="isFolder"
              label="文件夹"
              options={[
                {
                  label: '是',
                  value: 1,
                },
                {
                  label: '否',
                  value: 0,
                },
              ]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormRadio.Group
              name="state"
              label="状态"
              options={[
                {
                  label: '启用',
                  value: 1,
                },
                {
                  label: '禁用',
                  value: 0,
                },
              ]}
            />
          </ProForm.Group>
          {/* {dataTree && dataTree.length && organization ? (
            <Tree
              defaultExpandAll
              height={800}
              showLine={{ showLeafIcon: false }}
              showIcon={true}
              treeData={dataTree}
              defaultSelectedKeys={[organization?.parentId]}
              onSelect={(selectedKeys: React.Key[], info: any) => {
                if (info.selected) {
                  formRef.current?.setFieldsValue({
                    parentName: info.node.title,
                    parentId: info.node.key,
                  });
                } else {
                  formRef.current?.setFieldsValue({
                    parentName: undefined,
                    parentId: undefined,
                  });
                }
              }}
            />
          ) : (
            <Empty />
          )} */}
        </Spin>
      </DrawerForm>
    </>
  );
};
export default EditOrganization;
